package com.juneyao.bigdata.service.impl;

import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.SearchQuery;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * @author quanbiao
 * @date 2018-06-30
 * es 异步查询
 */
public class ElasticRunnable implements Callable<Long> {

    /**
     * es 模板
     */
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 查询条件
     */
    private SearchQuery searchQuery;

    /**
     * 计数器 实现线程同步
     */
    private CountDownLatch countDownLatch;

    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    @Override
    public Long call() throws Exception {
        long userCount = elasticsearchTemplate.count(searchQuery);
        countDownLatch.countDown();
        return userCount;
    }

    public ElasticsearchTemplate getElasticsearchTemplate() {
        return elasticsearchTemplate;
    }

    public void setElasticsearchTemplate(ElasticsearchTemplate elasticsearchTemplate) {
        this.elasticsearchTemplate = elasticsearchTemplate;
    }

    public SearchQuery getSearchQuery() {
        return searchQuery;
    }

    public void setSearchQuery(SearchQuery searchQuery) {
        this.searchQuery = searchQuery;
    }

    public CountDownLatch getCountDownLatch() {
        return countDownLatch;
    }

    public void setCountDownLatch(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    public ElasticRunnable(ElasticsearchTemplate elasticsearchTemplate, SearchQuery searchQuery, CountDownLatch countDownLatch) {
        this.elasticsearchTemplate = elasticsearchTemplate;
        this.searchQuery = searchQuery;
        this.countDownLatch = countDownLatch;
    }

    public ElasticRunnable() {
    }
}
